﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CloundUploader.Framework.Log;
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace CloundUploader.Framework.Engine
{
   public class PythonEngine:IEngine
   {
       private ScriptEngine engine;
       private ScriptScope scope;
       private IList<Script> scripts;
       private ILog Logger;
       private UploaderContext context;

       public PythonEngine()
       {
            engine = Python.CreateEngine();
            scope = engine.CreateScope();
            scripts=new List<Script>();
            Logger=new Log.Log();
            context = UploaderContext.Instance;
            scope.SetVariable("Context", context);
       }

       public void LoadScripts()
       {
           scripts.Add(new Script());
       }

       public void Excute()
       {
           foreach (var script in scripts.OrderByDescending(u=>u.Turn))
           {
               if (!script.Auto) continue;
               try
               {
                   engine.CreateScriptSourceFromString(script.ScriptCode, SourceCodeKind.AutoDetect);
               }
               catch (Exception ex)
               {
                   Logger.Error(script.ScriptCode, ex);
               }
           }
       }

       public void Excute(Script script)
       {
           try
           {
               engine.CreateScriptSourceFromString(script.ScriptCode, SourceCodeKind.AutoDetect);
           }
           catch (Exception ex)
           {
               Logger.Error(script.ScriptCode, ex);
           }

       }
    }
}
